/**
 * 表格的表注和表脚注
 */
import { v4 as uuid } from 'uuid'
import { getNumber, integerToAlphabet } from "@/utils/exampleTag"
import store from '@/store'

// 获取表注或表脚注的编号
export function getNumberFromTableFoot(tfootDom, act) {
  // 脚注使用abc字母编号，表注使用123数字编号
  const alphaFlag = act === 'footnote' ? 1 : 0
  const tr = tfootDom?.querySelector?.('.tr_' + act)
  const td = tr?.firstChild
  if (!tfootDom || !tr || !td) return alphaFlag ? integerToAlphabet(1) : 1
  const lastNumber = td.lastChild?.getAttribute?.('data-number') || ''
  if (lastNumber) {
    if (!alphaFlag) return parseInt(lastNumber) + 1
    let nextCharcode = lastNumber.charCodeAt(0) + 1
    nextCharcode = nextCharcode > 122 ? 97 : nextCharcode
    return String.fromCharCode(nextCharcode)
  }
  return alphaFlag ? integerToAlphabet(1) : 1
}

// 刷新表注的编号
export function resetTableNoteSiblingsNumber(node) {
  const dataLang = node.dataset.lang
  function walk(next) {
    if(!next) return
    const dataNumber = next.dataset.number
    if (next.classList.contains('table_note') && dataNumber && next.dataset.lang === dataLang) {
      const number = getNumber({ node: next, classList: ['table_note', dataLang], dataLang })
      next.setAttribute('data-number', number)
      if (next.nextElementSibling) {
        walk(next.nextElementSibling)
      }
    }
  }
  if(node.nextElementSibling) {
    walk(node.nextElementSibling)
  }
}

// 刷新表脚注的编号
export function resetTableFootnoteNumbers(tableDom, editor) {
  // 刷新正文中的标记和脚注的编号
  const tags = tableDom?.querySelectorAll?.('tbody span.table_footnote')
  if (!tags) return
  const tfootDom = tableDom.querySelector('tfoot tr.tr_table_footnote td')
  const length = tags.length
  const languageType = store.getters.languageType
  // 按中英文顺序添加表脚注
  let zhHTML = '', enHTML = ''
  for (let i = 0; i < length; i++) {
    const tag = tags[i]
    const number = integerToAlphabet(i+1)
    editor.undoManager.ignore(function() {
      tag.setAttribute('data-number', number)
    })

    const oldDomZh = tfootDom.querySelector(`.zh[data-referred-id="${tag.dataset.id}"]`)
    const oldDomEn = tfootDom.querySelector(`.en[data-referred-id="${tag.dataset.id}"]`)
    zhHTML += `
      <p class="table_footnote zh"
        data-referred-id="${tag.dataset.id}"
        data-number="${number}"
        data-type="table_footnote"
        data-lang="zh"
        data-note-id="${oldDomZh?.dataset?.noteId || uuid()}"
        data-id="${oldDomZh?.dataset?.id || uuid()}"
      >${oldDomZh?.textContent || '&#8203'}</p>
    `
    if (languageType !== 'both') continue
    enHTML += `
      <p class="table_footnote en"
      data-referred-id="${tag.dataset.id}"
      data-number="${number}"
      data-type="table_footnote"
      data-lang="en"
      data-note-id="${oldDomEn?.dataset?.noteId || uuid()}"
      data-id="${oldDomEn?.dataset?.id || uuid()}"
    >${oldDomEn?.textContent || '&#8203'}</p>
    `
  }
  editor.dom.setHTML(tfootDom, zhHTML + enHTML)
}

// 刷新正文章节中的表格编号
export function refreshTableNumbers(editor) {
  const doc = editor.getDoc()
  // 找到所有的正文页面，刷新其中的表格编号
  const pages = doc.querySelectorAll('.page-sheet.page-content')
  let tableNumber = 0
  pages.forEach(page => {
    const tableDoms = page.querySelectorAll('table.data-content-table:not(.term-block table)')
    tableDoms.forEach((tableDom) => {
      editor.dom.setAttrib(tableDom, 'data-number', ++tableNumber)
      // 同步更新表格表题上的编号显示
      tableDom.querySelectorAll('caption .caption').forEach((caption) => {
        editor.dom.setAttrib(caption, 'data-number', tableNumber)
      })
    })
  })
}
